package io.renren.modules.sys.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gisinfo.platform.components.auth.web.ws.client.AuthServiceClient;
import com.gisinfo.platform.components.auth.web.ws.client.WsPermissionResult;
import com.gisinfo.platform.components.auth.web.ws.client.WsUser;
import com.gisinfo.platform.components.oauth2.web.api.client.OAuthServiceClient;
import com.gisinfo.platform.components.oauth2.web.api.client.WsOAuthAccessToken;
import com.gisinfo.platform.components.oauth2.web.api.client.WsOAuthUserInfo;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.shiro.OAuth2Token;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther guqianbin
 * @date 2019/11/7 14:31
 **/
@Controller
@RequestMapping("/oauth-client")
public class OauthController extends AbstractController {
    private static final String OAUTH_URL = "http://59.202.42.175:8088/oauth2";//替换为实际地址
    private static final String CLIENT_ID = "8881d19b35d34f949592dbf189389c0b";//替换为实际参数
    private static final String CLIENT_SECRET = "87e4187d682441f1a587a0687fd92dd7";//替换为实际参数
    private static final String REDIRECT_URI = "http://10.19.33.32:8889/dangan/oauth-client/login";//回调接口地址
    private static final String SCOPE = "clientscope";//固定值
    private static final String AUTH_URL = "http://59.202.42.175:8088/userManager/ws";//替换为实际地址


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserDao sysUserDao;

    @RequestMapping("/login")
    public String codeLogin(HttpServletRequest request) throws Exception {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        WsOAuthAccessToken oauthAccessToken = new OAuthServiceClient(OAUTH_URL, CLIENT_ID, CLIENT_SECRET)
                .getWebPageAccessToken(CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI, SCOPE, state);
        if (oauthAccessToken == null) {
            System.out.println("获取access token失败.");
            return null;
        }
        WsOAuthUserInfo wsOAuthUserInfo = null;
        if (oauthAccessToken != null) {
            wsOAuthUserInfo = new OAuthServiceClient(OAUTH_URL, CLIENT_ID, CLIENT_SECRET)
                    .getSSOUserInfo(oauthAccessToken.getAccess_token());
        }
        if (wsOAuthUserInfo == null
                || wsOAuthUserInfo.getUsername() == null
                || "".equals(wsOAuthUserInfo.getUsername())) {
            System.out.println("未获取到单点登录用户信息.");
            return null;
        }
        AuthServiceClient client = new AuthServiceClient(AUTH_URL);
        WsPermissionResult auth = client.getPermissionByLoginName(wsOAuthUserInfo.getUsername(), null, null, null);

        WsUser user = null;
        if (auth.isSuccess()) {
            user = auth.getUser();
            System.out.println(JSON.toJSONString(user));
        }

        //5.根据当前登录用启信息，处理业务相关逻辑
        //TODO
        Map<String, Object> params = new HashMap<>();
        List<SysUserEntity> userEntities = sysUserDao.selectList(new QueryWrapper<SysUserEntity>().eq("oauth_user_id", user.getUserId()));
        SysUserEntity sysUserEntity = null;
        logger.info("查询到authid="+user.getUserId()+"用户数"+userEntities.size());
        if (CollectionUtil.isEmpty(userEntities)) {
            params.clear();
            params.put("sso_login_name", user.getLoginName());
            List<SysUserEntity> danganUsers = sysUserDao.selectByMap(params);
            logger.info("查询到sso_login_name="+user.getLoginName()+"用户数"+danganUsers.size());
            if (CollectionUtil.isNotEmpty(danganUsers)) {
                //TODO  绑定用户
                sysUserEntity = danganUsers.get(0);
                sysUserEntity.setOauthUserId(user.getUserId());
                sysUserDao.updateById(sysUserEntity);
            } else {
                params.clear();
                params.put("username", user.getLoginName());
                danganUsers = sysUserDao.selectByMap(params);
                logger.info("username="+user.getLoginName()+"用户数"+danganUsers.size());
                if (CollectionUtil.isNotEmpty(danganUsers)) {
                    //TODO  绑定用户
                    sysUserEntity = danganUsers.get(0);
                    sysUserEntity.setOauthUserId(user.getUserId());
                    sysUserDao.updateById(sysUserEntity);
                }else{
                    return "oauthError";
                }
            }
        } else {
            sysUserEntity = userEntities.get(0);
        }
        login(code, sysUserEntity, user);
        return "modules/dangan/danganIndex";
    }

    private void login(String code, SysUserEntity sysUserEntity, WsUser user) {
        //todo  进行登录
        Subject subject = ShiroUtils.getSubject();
        OAuth2Token token = new OAuth2Token(code, sysUserEntity.getUsername(), user.getUserId());
        token.setSysUserEntity(sysUserEntity);
        subject.login(token);
        boolean perm = SecurityUtils.getSubject().isPermitted("dangan:wsFile");
        System.out.println("授权结果：" + perm);
    }
}
